package com.scwatch.core.fulltext;

import com.scwatch.common.fulltext.LuceneIndexTemplate;
import com.scwatch.common.orm.LimitRequest;
import com.scwatch.common.orm.Limitable;
import com.scwatch.core.domain.Special;
import com.scwatch.core.domain.Task;
import com.scwatch.core.service.TaskService;
import org.apache.lucene.search.SortField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class SpecialFulltextGeneratorImpl implements SpecialFulltextGenerator {
	private final Logger logger = LoggerFactory
			.getLogger(SpecialFulltextGeneratorImpl.class);

	public void addDocument(final Special[] beans) {
		new Thread() {
			@Override
			public void run() {
				try {
					// 等待主线程结束，提交事务后，再运行。
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					logger.error(null, e);
				}
				for (Special bean : beans) {
				    if(     bean!=null &&
                            bean.getLevel()!=null && bean.getLevel().intValue()==0 &&
                            bean.getRecycleState()!=null && bean.getRecycleState().intValue()==0 &&
                            bean.getPublish()!=null && bean.getPublish().intValue()==0){

                        SortField sortField1 = new SortField("priority",SortField.INT,true);
                        SortField sortField2 = new SortField("createDate",SortField.LONG,true);
                        org.apache.lucene.search.Sort sort = new org.apache.lucene.search.Sort(sortField1,sortField2);
                        Limitable limitable = new LimitRequest(0,10);

				        Integer[] siteIds=new Integer[]{bean.getSite().getId()};
				        Integer[] includeIds=new Integer[]{bean.getId()};

                        List<Special> specialList=specialFulltextService.list(siteIds,null,includeIds,null,0,limitable,sort);
                        if(specialList!=null && specialList.size()>0){ //存在更新
                            specialFulltextService.updateDocument(bean.getId());
                        }else{
                            specialFulltextService.addDocument(bean.getId()); //不存在添加
                        }

                    }
				}
			}
		}.start();
	}

	public void updateDocument(final Special[] beans) {
		new Thread() {
			@Override
			public void run() {
				try {
					// 等待主线程结束，提交事务后，再运行。
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					logger.error(null, e);
				}
				for (Special bean : beans) {
                    if(bean!=null &&
                            bean.getLevel()!=null && bean.getLevel().intValue()==0 &&
                            bean.getRecycleState()!=null && bean.getRecycleState().intValue()==0 &&
                            bean.getPublish()!=null && bean.getPublish().intValue()==0){
                        specialFulltextService.updateDocument(bean.getId());
                    }
				}
			}
		}.start();
	}

	public void deleteDocuments(final Special[] beans) {
		for (Special bean : beans) {
			template.deleteDocuments(FSpecial.id(bean.getId()));
		}
	}

	public void addDocument(final Integer siteId,Integer userId) {
		String name = "ALL";
		Task task = taskService.save("spec: " + name, null, Task.FULLTEXT,
				userId, siteId);
		final Integer taskId = task.getId();
		new Thread() {
			@Override
			public void run() {
				try {
					specialFulltextService.addDocument(siteId, taskService,taskId);
					taskService.finish(taskId);
				} catch (Exception e) {
					taskService.abort(taskId);
					logger.error("create spec fulltext index error!", e);
				}
			}
		}.start();
	}

	private TaskService taskService;
	private SpecialFulltextService specialFulltextService;
	private LuceneIndexTemplate template;

	@Autowired
	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

    @Autowired
    public void setSpecialFulltextService(SpecialFulltextService specialFulltextService) {
        this.specialFulltextService = specialFulltextService;
    }


	@Autowired
	public void setLuceneIndexTemplate(LuceneIndexTemplate template) {
		this.template = template;
	}
}
